package faf.web;

import java.io.PrintWriter;
import java.util.List;

import javassist.bytecode.Descriptor.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import faf.business.ReportManager;
import faf.business.SurveyManager;
import faf.entities.Account;
import faf.entities.Survey;

public class FullCsvReportController  implements Controller {
	SurveyManager surveyManager;
	ReportManager reportManager;
	
	public ReportManager getReportManager() {
		return reportManager;
	}

	public void setReportManager(ReportManager reportManager) {
		this.reportManager = reportManager;
	}

	public SurveyManager getSurveyManager() {
		return surveyManager;
	}

	public void setSurveyManager(SurveyManager manager) {
		this.surveyManager = manager;
	}	
	
	@Override
	public ModelAndView handleRequest(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		long id = Long.parseLong(request.getParameter("id"));

		Survey survey = surveyManager.get(id);
		Account user = (Account) request.getSession().getAttribute("user");
		
		if (reportManager.canSeeFullreport(user, survey)==true){
		 	response.setContentType("text/csv" );
		 	//response.setContentType( "application/csv" );   
		 	response.setHeader("Content-disposition",
		   	"attachment; filename=\""+ survey.getTitle() +".csv\"" );
		 	PrintWriter out = response.getWriter();
		 	List<List<String>> report = reportManager.getFullCsvReport(survey.getId());
		 	
		 	for(List<String> ligne : report) {
		 		java.util.Iterator<String> iterator = ligne.iterator();
		 		
		 		while(iterator.hasNext() == true) {
		 			String value = iterator.next();
		 			out.print(value);
		 			if(iterator.hasNext() == true)
		 				out.print(",");
		 		}
		 		out.println();
		 	}
		}
		
		return null;
	}

}
